from fastapi import FastAPI, APIRouter, Depends, Request
from models.Models import User
from db.DBUtil import DBUtil
from utils.result_back import success, fail
from auth.auth import *

router = APIRouter()
app = FastAPI()




class Item(BaseModel):
    username: str
    password: str


@router.post("/login")
def get_user(item: Item, Authorize: AuthJWT = Depends()):
    db_util = DBUtil()
    session = db_util.get_session()
    user = session.query(User).filter(User.username == item.username, User.password == item.password).first()
    if user:
        # resources = session.query(Resource). \
        #     join(RoleResources, RoleResources.resource_id == Resource.id). \
        #     join(UserRoles, UserRoles.role_id == RoleResources.role_id). \
        #     filter(UserRoles.user_id == user.id).all()
        # authorities = []
        # for resource in resources:
        #     authorities.append(resource.permission)
        access_token = Authorize.create_access_token(subject=user.username)
        result = {"user": user, "access_token": access_token}
        db_util.close()
        return success(result)
    else:
        db_util.close()
        return fail('账号或密码错误')


@router.get("/auth/userInfo")
def user_info(Authorize: AuthJWT = Depends()):
    Authorize.jwt_required()
    current_user = Authorize.get_jwt_subject()
    db_util = DBUtil()
    session = db_util.get_session()
    user = session.query(User).filter(User.username == current_user).first()
    # roles = session.query(Role). \
    #     join(UserRoles, UserRoles.role_id == Role.id). \
    #     filter(UserRoles.user_id == user.id).all()
    # role_arr = []
    # for role in roles:
    #     role_arr.append(role.name)
    # result = {"user": user, "roles": role_arr}
    db_util.close()
    return success(user)
